package com.emm.yixun.mobile.ui.analysis;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.customview.AbstractDemoChart;
import com.emm.yixun.mobile.model.GetSalesTargetList;
import com.emm.yixun.mobile.model.GetSalesTargetList.MonthTargetList;
import com.emm.yixun.mobile.model.GetSalesTargetList.MonthTotalCompletetList;
import com.emm.yixun.mobile.model.GetSalesTargetList.MonthTotalTargetList;
import com.emm.yixun.mobile.model.GetSalesTargetList.TargetCompleteList;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * 
 * <p>
 * <b>Title：</b> 销售指标
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月6日 下午4:12:27
 */
public class SalesTargetActivity extends SwipeBackActivity {

	private static final String TAG = "SalesTargetActivity";

	/** 折线图 */
	LinearLayout linear, linear2;

	LinearLayout sort_textview, screen_textview;

	TextView lines1_bg, lines2_bg;

	TextView colors_text, colors_text2;

	/** 标题 */
	TextView title_main;

	/** back按钮 */
	ImageView back_btn;

	/** 侧滑关闭框架 */
	private SwipeBackLayout mSwipeBackLayout;

	@Override
	protected void onResume() {
		BaseActivity.activity = this;
		super.onResume();
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.salestarget_activity);

		SetSwipeBackLayout(mSwipeBackLayout);

		BaseActivity.activity = this;

		initView();

		SetRelativiLayoutPadding(R.id.main_head_top_rela);

		initBtn();
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化view
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午4:40:09
	 */
	private void initView() {
		linear = (LinearLayout) findViewById(R.id.linear);
		sort_textview = (LinearLayout) findViewById(R.id.sort_textview);
		screen_textview = (LinearLayout) findViewById(R.id.screen_textview);
		lines1_bg = (TextView) findViewById(R.id.lines1_bg);
		lines2_bg = (TextView) findViewById(R.id.lines2_bg);
		colors_text = (TextView) findViewById(R.id.colors_text);
		colors_text2 = (TextView) findViewById(R.id.colors_text2);
		linear2 = (LinearLayout) findViewById(R.id.linear2);
		title_main = (TextView) findViewById(R.id.title_main);
		title_main.setText("销售指标");
		back_btn = (ImageView) findViewById(R.id.back_btn);
		getSalesTargetList("1");
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化监听事件
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午4:40:17
	 */
	private void initBtn() {
		sort_textview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				colors_text.setTextColor(Color.parseColor("#FCA639"));
				colors_text2.setTextColor(Color.parseColor("#3E3C3D"));
				lines1_bg.setVisibility(View.VISIBLE);
				lines2_bg.setVisibility(View.INVISIBLE);
				getSalesTargetList("1");
			}
		});
		screen_textview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				colors_text.setTextColor(Color.parseColor("#3E3C3D"));
				colors_text2.setTextColor(Color.parseColor("#FCA639"));
				lines1_bg.setVisibility(View.INVISIBLE);
				lines2_bg.setVisibility(View.VISIBLE);
				getSalesTargetList("2");
			}
		});
		back_btn.setVisibility(View.VISIBLE);
		back_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private int YMIN = 0;
	private int XMAX = 8;
	private int XMIN = 0;
	private int YMAX = 13;

	/** 图例集合 */
	String[] titles = new String[] { "指标   ", "完成情况" };

	/** 月份集合 */
	double[] doublelist = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

	/** 月指标数列表 */
	double[] doublelist1;

	/** 月指标完成数列表 */
	double[] doublelist2;

	/** 累计月指标列表 */
	double[] doublelist3;

	/** 累计月完成数列表 */
	double[] doublelist4;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 设置属性
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param context
	 * @param titles
	 *            图例集合
	 * @param doublelist
	 *            月份集合
	 * @param doublelist1
	 *            月指标数列表
	 * @param doublelist2
	 *            月指标完成数列表
	 * @return
	 * @author tangxin
	 * @date 2016年12月7日 下午4:41:05
	 */
	public View execute(Context context, String[] titles, double[] doublelist, double[] doublelist1,
			double[] doublelist2) {
		List<double[]> values = new ArrayList<double[]>();// values:两条折线的Y轴的值的集合
		values.add(doublelist1);
		values.add(doublelist2);
		int[] colors = new int[] { Color.parseColor("#3E6697"), Color.parseColor("#D34A4A") };// 两条折线的颜色的集合
		PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE, PointStyle.DIAMOND };// 折线上点的样式
		XYMultipleSeriesRenderer renderer = AbstractDemoChart.buildRenderer(colors, styles);// 折线图的渲染器
		int length = renderer.getSeriesRendererCount();
		NumberFormat nf = new DecimalFormat(" #.#");
		for (int i = 0; i < length; i++) {
			if (i == 0) {
				((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setChartValuesTextAlign(Align.RIGHT);
			} else {
				((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setChartValuesFormat(nf);
				((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setChartValuesTextAlign(Align.LEFT);
			}
			((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setFillPoints(true);// 设置图上的点为实心
			((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setDisplayChartValues(true);// 设置折线上的点是否显示
		}
		renderer.setYLabels(8);// 设置Y轴刻度个数（貌似不太准确）
		renderer.setYAxisMin(0);// 设置Y轴最小值
		renderer.setYAxisMax(YMAX);// 设置Y轴最大值
		renderer.setXAxisMin(0);// 设置X轴最小值
		renderer.setXAxisMax(5);// 设置X轴默认显示几个月份
		renderer.setShowGrid(true);// 是否显示网格
		renderer.setXLabels(0);// 设置是否显示Y轴（如果设置为1则Y轴显示，但是当你向右滑动后，会在第五个月出现这个Y轴，之前的又不见了）
		renderer.setXLabelsAlign(Align.RIGHT);// 刻度线与刻度标注之间的相对位置关系(此时表示的是1月在1月的X轴坐标的左边)
		renderer.setYLabelsAlign(Align.RIGHT);
		renderer.setZoomButtonsVisible(false);// 是否显示放大缩小按钮
		renderer.setLabelsTextSize(EmmApplication.dip2px(10));// 设置坐标轴上标签文字的大小
		renderer.setLegendTextSize(EmmApplication.dip2px(12));// 设置图例文字大小
		renderer.setAxisTitleTextSize(EmmApplication.dip2px(10));// 设置XY轴标题文本大小
		renderer.setPointSize(10f);// 设置点的大小
		renderer.setChartValuesTextSize(EmmApplication.dip2px(8));// 点的值的文字大小
		renderer.setLegendHeight(EmmApplication.dip2px(30));// 设置图例高度
		renderer.setPanLimits(new double[] { 0, 13, 0, 12 });// 设置拖动时X轴Y轴允许的最大值最小值.
		renderer.setZoomLimits(null);// 设置放大缩小时X轴Y轴允许的最大最小值.
		renderer.setGridColor(Color.parseColor("#E4E7E4"));// 设置网格颜色
		renderer.setXLabelsColor(Color.parseColor("#B1B1B1")); // X Y轴刻度颜色
		renderer.setYLabelsColor(0, Color.parseColor("#B1B1B1"));
		renderer.setGridColor(Color.parseColor("#E4E7E4"));// 设置网格颜色
		renderer.setAxesColor(Color.parseColor("#00767676"));// 设置坐标轴颜色
		renderer.setFitLegend(true);// 调整合适的位置
		renderer.setXTitle("月份");
		renderer.setYTitle("金额/万元");
		renderer.setMargins(new int[] { EmmApplication.dip2px(10), EmmApplication.dip2px(60), EmmApplication.dip2px(25),
				EmmApplication.dip2px(10) });// 设置视图位置(上左下右)
		renderer.setPointSize(5f);// 设置点的值
		renderer.setApplyBackgroundColor(true);// 是否设置外层View背景色
		renderer.setBackgroundColor(Color.parseColor("#ffffff"));// 网格背景色
		renderer.setMarginsColor(Color.parseColor("#ffffff"));// 外层View背景色

		for (int i = 0; i < 12; i++) {
			renderer.addXTextLabel(i + 1, (i + 1) + "月");
		}

		XYMultipleSeriesDataset dataset = AbstractDemoChart.buildDataset(titles, values);

		View v = ChartFactory.getLineChartView(context, dataset, renderer);

		return v;
	}

	/**
	 * <p>
	 * <b>Title：</b> 将统计图添加到view
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param v
	 * @author tangxin
	 * @date 2016年12月7日 下午4:42:15
	 */
	private void SetLinear1View(View v) {
		linear.removeAllViews();
		linear.addView(v);
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 将统计图添加到view
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param v
	 * @author tangxin
	 * @date 2016年12月7日 下午4:42:15
	 */
	private void SetLinear2View(View v) {
		linear2.removeAllViews();
		linear2.addView(v);
	}

	/**
	 * 查询销售指标
	 */
	GetSalesTargetList getsales;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 查询销售指标
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param targetType
	 * @author tangxin
	 * @date 2016年12月7日 下午4:42:50
	 */
	private void getSalesTargetList(String targetType) {
		EmmApplication.updateUrl("getSalesTargetList");
		Map<String, String> map = new HashMap<String, String>();
		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("projectCode", EmmApplication.getProjectCode());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("targetType", targetType);
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v("getSalesTargetList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Loading.hideDialogForLoading();
				Loading.showDialogForLoading(SalesTargetActivity.this, "正在加载...", false, true, 60000);
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v(TAG, "content===>" + content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getsales = JSONObject.parseObject(resData.toString(), GetSalesTargetList.class);

				if ("1".equals(getsales.getResult())) {
					Log.v("获取成功", "");

					if (null != getsales.getMonthTargetList() && getsales.getMonthTargetList().size() > 0) {
						doublelist1 = new double[getsales.getMonthTargetList().size()];
						getMax_forMax1(getsales.getMonthTargetList());
						for (int i = 0; i < getsales.getMonthTargetList().size(); i++) {
							doublelist1[i] = Double.valueOf(getsales.getMonthTargetList().get(i).getTargetNum())
									.doubleValue();
						}
					} else {
						doublelist1 = new double[1];
						doublelist1[0] = 0;
					}

					if (null != getsales.getTargetCompleteList() && getsales.getTargetCompleteList().size() > 0) {
						doublelist2 = new double[getsales.getTargetCompleteList().size()];
						getMax_forMax2(getsales.getTargetCompleteList());
						for (int i = 0; i < getsales.getTargetCompleteList().size(); i++) {
							doublelist2[i] = Double.valueOf(getsales.getTargetCompleteList().get(i).getCompleteNum())
									.doubleValue();
						}
					} else {
						doublelist2 = new double[1];
						doublelist2[0] = 0;
					}

					int count = (max1 > max2 ? max1 : max2);// 取月指标中的最大值

					YMAX = count + count / 4;

					SetLinear1View(execute(SalesTargetActivity.this, titles, doublelist, doublelist1, doublelist2));

					if (null != getsales.getMonthTotalTargetList() && getsales.getMonthTotalTargetList().size() > 0) {
						doublelist3 = new double[getsales.getMonthTotalTargetList().size()];
						getMax_forMax3(getsales.getMonthTotalTargetList());
						for (int i = 0; i < getsales.getMonthTotalTargetList().size(); i++) {
							doublelist3[i] = Double
									.valueOf(getsales.getMonthTotalTargetList().get(i).getMt_targetNum()).doubleValue();
						}
					} else {
						doublelist3 = new double[1];
						doublelist3[0] = 0;
					}

					if (null != getsales.getMonthTotalCompletetList()
							&& getsales.getMonthTotalCompletetList().size() > 0) {
						doublelist4 = new double[getsales.getMonthTotalCompletetList().size()];
						getMax_forMax4(getsales.getMonthTotalCompletetList());
						for (int i = 0; i < getsales.getMonthTotalCompletetList().size(); i++) {
							doublelist4[i] = Double.valueOf(
									getsales.getMonthTotalCompletetList().get(i).getMt_completeNum()).doubleValue();
						}
					} else {
						doublelist4 = new double[1];
						doublelist4[0] = 0;
					}
					int count2 = (max3 > max4 ? max3 : max4);

					YMAX = count2 + count2 / 4;
					SetLinear2View(execute(SalesTargetActivity.this, titles, doublelist, doublelist3, doublelist4));

				} else {
					EmmApplication.T(getsales.getErrorMsg().toString());
					Log.v("获取失败", "errorCode:" + getsales.getErrorCode().toString() + "errorMsg:"
							+ getsales.getErrorMsg().toString());
				}
			}
		});
	}

	int max1 = 10;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 得到最大值
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param getMonthTargetList
	 * @author tangxin
	 * @date 2016年12月7日 下午4:43:47
	 */
	public void getMax_forMax1(ArrayList<MonthTargetList> getMonthTargetList) {
		String maxp = getMonthTargetList.get(0).getTargetNum();
		for (int x = 1; x < getMonthTargetList.size(); x++) {
			if (Double.valueOf(maxp).doubleValue() < Double.valueOf(getMonthTargetList.get(x).getTargetNum())
					.doubleValue()) {
				maxp = getMonthTargetList.get(x).getTargetNum();
			}
		}
		if (Double.valueOf(EmmApplication.drop2(maxp)).doubleValue() < 10)
			max1 = 10;
		else
			max1 = (int) (Double.valueOf(EmmApplication.drop2(maxp)).doubleValue() + 1);
		Log.v(TAG, "最大值：" + max1);
	}

	int max2 = 10;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 得到最大值
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param getMonthTargetList
	 * @author tangxin
	 * @date 2016年12月7日 下午4:43:47
	 */
	public void getMax_forMax2(ArrayList<TargetCompleteList> targetCompleteList) {
		String maxp = targetCompleteList.get(0).getCompleteNum();
		for (int x = 1; x < targetCompleteList.size(); x++) {
			if (Double.valueOf(maxp).doubleValue() < Double.valueOf(targetCompleteList.get(x).getCompleteNum())
					.doubleValue()) {
				maxp = targetCompleteList.get(x).getCompleteNum();
			}
		}
		if (Double.valueOf(EmmApplication.drop2(maxp)).doubleValue() < 10)
			max2 = 10;
		else
			max2 = (int) (Double.valueOf(EmmApplication.drop2(maxp)).doubleValue() + 1);
		Log.v(TAG, "最大值：" + max2);
	}

	int max3 = 10;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 得到最大值
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param getMonthTargetList
	 * @author tangxin
	 * @date 2016年12月7日 下午4:43:47
	 */
	public void getMax_forMax3(ArrayList<MonthTotalTargetList> monthTotalTargetList) {
		String maxp = monthTotalTargetList.get(0).getMt_targetNum();
		for (int x = 1; x < monthTotalTargetList.size(); x++) {
			if (Double.valueOf(maxp).doubleValue() < Double.valueOf(monthTotalTargetList.get(x).getMt_targetNum())
					.doubleValue()) {
				maxp = monthTotalTargetList.get(x).getMt_targetNum();
			}
		}
		if (Double.valueOf(EmmApplication.drop2(maxp)).doubleValue() < 10)
			max3 = 10;
		else
			max3 = (int) (Double.valueOf(EmmApplication.drop2(maxp)).doubleValue() + 1);
		Log.v(TAG, "最大值：" + max3);
	}

	int max4 = 10;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 得到最大值
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param getMonthTargetList
	 * @author tangxin
	 * @date 2016年12月7日 下午4:43:47
	 */
	public void getMax_forMax4(ArrayList<MonthTotalCompletetList> monthTotalCompletetList) {
		String maxp = monthTotalCompletetList.get(0).getMt_completeNum();
		for (int x = 1; x < monthTotalCompletetList.size(); x++) {
			if (Double.valueOf(maxp).doubleValue() < Double.valueOf(monthTotalCompletetList.get(x).getMt_completeNum())
					.doubleValue()) {
				maxp = monthTotalCompletetList.get(x).getMt_completeNum();
			}
		}
		if (Double.valueOf(EmmApplication.drop2(maxp)).doubleValue() < 10)
			max4 = 10;
		else
			max4 = (int) (Double.valueOf(EmmApplication.drop2(maxp)).doubleValue() + 1);
		Log.v(TAG, "最大值：" + max4);
	}
}
